<template>
  <div class="station">
    <div class="search">
      <el-button type="primary" @click="addStation(0)" plain="plain" v-if="menuFlag == '14'" class="addPost"
        size="small">添加岗位</el-button>
      <span v-else-if="menuFlag == '15'">
        <el-input placeholder="请输入内容" v-model="keyword" class="input-with-select input-search" style="width: 220px"
          @keydown.enter.native="search" size="small">
          <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
        </el-input>
        <el-button type="success" @click="derive()" plain="plain" class="exit" size="small">导出</el-button>
      </span>
      <!-- <el-button v-else type="primary" @click="addGroups(0)" plain="plain" class="addGroups" size="small">添加职能组
      </el-button> -->
    </div>
    <base-table ref="baseTable" :tableSetting="tableSetting" @handleCommon="handleCommon" :menuFlag="menuFlag">
    </base-table>
    <!-- 岗位弹框 -->
    <el-dialog :title="titleStation" :close-on-click-modal="false" :show-close="false" :visible.sync="dialogStation"
      width="500px" center>
      <el-form status-icon label-width="120px" :model="form" :rules="rules" ref="form" class="demo-ruleForm">
        <!-- <el-form-item label="所属部门" placeholder="请选择所属部门" prop="deptId">
          <el-cascader :options="postData" v-model="selectedOptions"
            :props="{ checkStrictly: true, multiple: true, emitPath: false }" @change="handleChoosedepartment">
          </el-cascader>
        </el-form-item> -->
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入岗位名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close('form')">取 消</el-button>
        <el-button type="primary" @click="save('form')" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 业绩属性弹框 -->
    <el-dialog title="业绩属性管理" :close-on-click-modal="false" :show-close="false" :visible.sync="dialogMance" width="500px"
      center>
      <el-tree :data="propertyList" show-checkbox node-key="id" :default-checked-keys="checkTree" :props="defaultProps"
        ref="tree"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMance = false">取 消</el-button>
        <el-button type="primary" @click="beture" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import baseTable from "@/components/table/baseTable";
import menuleft from "@/components/menuItem/menuleft.vue";
import {
  selectSysPostList,
  selectUserList,
  selectFunGroupList,
  insertSysPost,
  updateSysPost,
  deletePost,
  insertFunctionGroup,
  updateFunctionGroup,
  deleteFunctionGroup,
  selectAllFunctionAttr,
  selectGroupAttr,
  exportEmpInfos,
  insertFunctionAttr,
  getdeptList,
} from "@/service/Api.js"; // 接口
// import { exportEmpInfos } from "../../../service/Api";

export default {
  components: { baseTable, menuleft },
  name: "companyMent",
  props: ["menuFlag"],
  data() {
    var validatedeptId = (rule, value, callback) => {
      if (this.selectedOptions.length === 0) {
        callback(new Error("请选择所属部门"));
      }
      else {
        callback();
      }
    };
    return {
      tableSetting: {
        tableApiFn: selectSysPostList,
          options: [{ prop: "name", label: "岗位名称" }],
          btns: [
            { text: "修改", size: "mini", handleName: "addStation" },
            {
              text: "删除",
              size: "mini",
              handleName: "remove",
              type: "danger",
            },
          ],
      },
      pn: 1,
      ps: 10,
      keyword: "",
      // 岗位管理
      dialogStation: false,
      titleStation: "",
      loading: false,
      form: {
        name: "",
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        deptId: [
          { required: true, validator: validatedeptId, trigger: "change" },
        ],
      },
      static: "",
      flag: "",
      id: "",
      fid: "",
      // 业绩
      formMance: {
        name: "",
      },
      dialogMance: false,
      propertyList: [],
      defaultProps: {
        label: "name",
      },
      checkTree: [],
      postData: [],
      selectedOptions: [], //部门绑定数组
    };
  },
  watch: {
    menuFlag(val) {
      if (val == 14) {
        this.tableSetting = {
          tableApiFn: selectSysPostList,
          options: [{ prop: "name", label: "岗位名称" }],
          btns: [
            { text: "修改", size: "mini", handleName: "addStation" },
            {
              text: "删除",
              size: "mini",
              handleName: "remove",
              type: "danger",
            },
          ],
        };
      } else if (val == 15) {
        this.tableSetting = {
          tableApiFn: selectUserList,
          defaulteParams: {
            keyword: this.keyword,
          },
          options: [
            { prop: "id", label: "员工编号" },
            { prop: "name", label: "员工姓名" },
            { prop: "phone", label: "手机号" },
            { prop: "qqAccount", label: "QQ" },
            { prop: "email", label: "企业邮箱" },
            { prop: "deptName", label: "岗位" },
          ],
        };
      } 
      // else if (val == 16) {
      //   this.tableSetting = {
      //     tableApiFn: selectFunGroupList,
      //     options: [{ prop: "name", label: "职能组名称" }],
      //     btns: [
      //       { text: "成员管理", size: "mini", handleName: "handleExport" },
      //       {
      //         text: "业绩属性管理",
      //         size: "mini",
      //         handleName: "performance",
      //         type: "success",
      //       },
      //       { text: "修改", size: "mini", handleName: "addGroups" },
      //       {
      //         text: "删除",
      //         size: "mini",
      //         handleName: "remove",
      //         type: "danger",
      //       },
      //     ],
      //   };
      // }
      setTimeout(() => {
        this.$refs.baseTable.initData();
      }, 10);
    },
  },
  created() {
    this.getdept();
  },
  methods: {
    getdept() {
      getdeptList().then((res) => {
        if (res.code === 0) {
          this.treedata = [
            {
              name: "全部部门",
              id: "",
              children: res.data,
            },
          ];
          this.postData = this.TreeDataSource(res.data);
        }
      });
    },
    // 递归替换属性名
    TreeDataSource(arr) {
      return arr.map((v, i) => {
        return {
          ...v,
          value: v.id,
          label: v.name,
          children: v.children ? this.TreeDataSource(v.children) : "",
        };
      });
    },
    //选择部门
    handleChoosedepartment(value) {
    },
    handleCommon(name, row, idx) {
      if (this[name]) {
        this[name](row, idx);
      }
    },
    handleExport(row, id) {
      // this.$router.push({ path: "/member", query: { id: row.id } });
      this.$emit("toMember", row.id);
    },
    //删除-岗位和职能组
    remove(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          let url;
          console.log(row.upTime); //upTime-只存在职能组
          row.upTime
            ? (url = deleteFunctionGroup(row.id))
            : (url = deletePost(row.id));
          url.then((res) => {
            if (res.code == 0) {
              this.$message.success("删除成功!");
              this.$refs.baseTable.initData();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => { });
    },
    //关闭弹框
    close(formName) {
      this.selectedOptions = [];
      this.$refs[formName].resetFields();
      this.dialogStation = false;
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          let opt = this.selectedOptions.join(",")
          let data = {
            id: this.id,
            name: this.form.name,
            deptId: opt,
          };
          let data2 = {
            name: this.form.name,
            deptId: opt,
          };
          // this.static 0-岗位添加 1-岗位修改 2-职能组添加 3-职能组修改
          this.static == 0
            ? (url = insertSysPost(data))
            : this.static == 1
              ? (url = updateSysPost(data))
              : this.static == 2
                ? (url = insertFunctionGroup(data2))
                : (url = updateFunctionGroup(data));
          url.then((res) => {
            console.log(res);
            if (res.code == 0) {
              this.$refs.baseTable.initData();
              this.$message.success("操作成功!");
              this.close("form");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 岗位-添加/修改
    addStation(row) {
      this.flag = 0;
      if (row == 0) {
        this.titleStation = "添加岗位";
        this.static = 0;
        this.id = "";
        this.form.name = "";
      } else {
        this.titleStation = "修改岗位";
        this.static = 1;
        this.id = row.id;
        this.form.name = row.name;
      }
      this.dialogStation = true;
    },
    // 员工-查询
    search() {
      this.tableSetting.defaulteParams.keyword = this.keyword;
      setTimeout(() => {
        this.$refs.baseTable.initData();
      }, 10);
    },
    //员工-导出
    derive() {
      let data = {
        // pn: this.pn,
        // ps: this.ps,
        keyword: this.keyword,
      }
      this.$confirm("此操作将导出数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        // const iframe = document.createElement("iframe");
        // iframe.style.display = "none";
        // iframe.style.height = 0;
        // iframe.src = `/api/admin/company/exportEmpInfo?keyword=${this.keyword}`;
        // // 5分钟之后删除
        // document.body.appendChild(iframe);
        // setTimeout(() => {
        //   iframe.parentNode.removeChild(iframe);
        // }, 5 * 6 * 1000);
        exportEmpInfos(data).then(res => {
          let blob = new Blob([res], {
            // type: "application/vnd.ms-excel;charset=UTF-8",
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
          });
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement("a"); // 创建a标签
          link.setAttribute('download', new Date().getTime() + '.xlsx')
          document.body.appendChild(link)
          link.download = "员工通讯录"
          link.href = url;
          link.click();
          URL.revokeObjectURL(url); // 释放内存
        })
      });
    },


    // 导出
    // derive() {
    //   this.$message.closeAll();
    //   this.$message.info("导出中，请稍后~");
    //   this.export()
    // },
    // export() {
    //   // 获取数据用的参数
    //   const params = {
    //     pn: this.pn,
    //     ps: this.ps,
    //     keyword: this.keyword,
    //   };
    //   // 创建当前时间字符串，生成文件名称时使用
    //   const time = this.getCurentTime()
    //   // 调用后台接口，获取文件流
    //   exportEmpInfos(params).then((res) => {
    //     // 转化为blob对象
    //     let blob = new Blob([res.data], {
    //       type: "application/octet-stream",
    //     });
    //     let filename = "" + time + '.xls'
    //     // 将blob对象转为一个URL
    //     var blobURL = window.URL.createObjectURL(blob);
    //     // 创建一个a标签
    //     var tempLink = document.createElement("a");
    //     // 隐藏a标签
    //     tempLink.style.display = "none";
    //     // 设置a标签的href属性为blob对象转化的URL
    //     tempLink.href = blobURL;
    //     // 给a标签添加下载属性
    //     tempLink.setAttribute("download", filename);
    //     if (typeof tempLink.download === "undefined") {
    //       tempLink.setAttribute("target", "_blank");
    //     }
    //     // 将a标签添加到body当中
    //     document.body.appendChild(tempLink);
    //     // 启动下载
    //     tempLink.click();
    //     // 下载完毕删除a标签
    //     document.body.removeChild(tempLink);
    //     window.URL.revokeObjectURL(blobURL);
    //     this.$message({
    //       message: "导出成功~",
    //       type: "success",
    //     });
    //   })
    // },
    // getCurentTime() {
    //   var date = new Date();
    //   //以下代码依次是获取当前时间的年月日时分秒
    //   var year = date.getFullYear();
    //   var month = date.getMonth() + 1;
    //   var strDate = date.getDate();
    //   var minute = date.getMinutes();
    //   var hour = date.getHours();
    //   var second = date.getSeconds();
    //   //固定时间格式
    //   if (month >= 1 && month <= 9) {
    //     month = "0" + month;
    //   }
    //   if (strDate >= 0 && strDate <= 9) {
    //     strDate = "0" + strDate;
    //   }
    //   if (hour >= 0 && hour <= 9) {
    //     hour = "0" + hour;
    //   }
    //   if (minute >= 0 && minute <= 9) {
    //     minute = "0" + minute;
    //   }
    //   if (second >= 0 && second <= 9) {
    //     second = "0" + second;
    //   }
    //   var currentdate = "_" + year + month + strDate + hour + minute + second;
    //   return currentdate;
    // },

    // 职能组--添加/修改
    addGroups(row) {
      this.flag = 1;
      if (row == 0) {
        this.titleStation = "添加职能组";
        this.static = 2;
        this.id = "";
        this.form.name = "";
      } else {
        this.titleStation = "修改职能组";
        this.static = 3;
        this.id = row.id;
        this.form.name = row.name;
        this.selectedOptions = row.deptId.split(",");
      }
      this.dialogStation = true;
    },
    // 业绩属性
    performance(row) {
      this.id = row.id;
      selectAllFunctionAttr().then((res) => {
        if (res.code == 0) {
          this.propertyList = res.data;
          this.checkPer(row.id);
        }
      });
      this.dialogMance = true;
    },
    checkPer(id) {
      this.checkTree = [];
      selectGroupAttr(id).then((res) => {
        if (res.code == 0) {
          if (res.data.length > 0) {
            let arr = [];
            res.data.forEach((element, index) => {
              arr.push(element.id);
            });
            this.checkTree = arr;
          } else {
            this.checkTree = [];
          }
        }
      });
    },
    beture() {
      let keyList = this.$refs.tree.getCheckedKeys(true);
      console.log(keyList);
      insertFunctionAttr(this.id, keyList).then((res) => {
        if (res.code == 0) {
          this.$message.success("操作成功~");
          this.dialogMance = false;
        }
      });
    },
  },
};
</script>

<style scoped>
.search span {
  display: flex;
  justify-content: space-between;
}

.addPost {
  margin-bottom: 15px;
}

.input-search,
.exit,
.addGroups {
  margin-bottom: 15px;
}
</style>
